<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>进制</title>
</head>

<body>
    <script>
        class Stack {
            // 构造方法
            constructor() {
                this.item = [];
            }
            push(element) {
                this.item.push(element);
            }
            pop() {
                return this.item.pop();
            }
            peek() {
                return this.item[this.item.length - 1];
            }
            isEmpty() {
                return this.item.length === 0;
            }
            clear() {
                this.item == [];
            }
            size() {
                return this.item.length;
            }
            toString() {
                return this.item.toString();
            }
        }

        function baseConverter(decNumber, base) {
            let number = decNumber; //商
            let rem; // 余数
            const remstack = new Stack();
            const digits = '0123456789ABCDEF';
            let baseString = '';
            if (!(base >= 2 && base <= 16)) {
                return '';
            }
            while (number > 0) {
                rem = Math.floor(number % base);
                remstack.push(rem);
                number = Math.floor(number / base);
            }
            while (!remstack.isEmpty()) {
                baseString += digits[remstack.pop()];
            }
            return baseString;
        }
        document.write(baseConverter(100345, 2));
        document.write(baseConverter(100345, 8));
        document.write(baseConverter(100345, 16));
    </script>
</body>

</html>